package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient storageClient;  //上传对象

    @Autowired
    private FdfsWebServer fdfsWebServer; //获取存储服务器地址

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference
    private CommentApi commentApi;

    /**
     * 分页查询视频列表
     *  key : page+"_"+size
     *
     *  videoList:1_10
     *  videoList:2_10
     *  videoList:3_10
     *
     *  好友动态列表
     *     用户id，page，size
     *     value=friendPublish
     *             ：friendPublish:1_1_10
     *             ：friendPublish:1_2_10
     *
     *             ：friendPublish:2_1_10
     *             ：friendPublish:2_2_10
     *     key= 用户id_page_sise
     *
     *  好友发布动态
     *     1号好友，发布动态
     *
     *
     */
    @Cacheable(value="videoList",key="#page + '_' +  #pagesize")
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1、调用api分页查询数据列表  PageResult<Video>
        PageResult result = videoApi.findAll(page,pagesize);
        //2、获取分页数据中数据列表   List<Video>
        List<Video> items = (List<Video>) result.getItems();
        //3、循环遍历数据集合，一个video构造一个vo
        List<VideoVo> list = new ArrayList<>();
        if(items != null) {
            for (Video item : items) {
                UserInfo info = userInfoApi.findById(item.getUserId());
                VideoVo vo = new VideoVo();
                BeanUtils.copyProperties(info,vo);
                BeanUtils.copyProperties(item,vo);
                vo.setCover(item.getPicUrl());
                vo.setId(item.getId().toHexString());
                vo.setSignature(item.getText());//签名

                //从redis中获取操作记录，如果存在返回1，不存在返回0
                String key = "followUser_"+UserHolder.getUserId()+"_"+item.getUserId();
                if(redisTemplate.hasKey(key)) {
                    vo.setHasFocus(1); //TODO 是否关注
                }else{
                    vo.setHasFocus(0); //TODO 是否关注
                }
                String likekey="video_like_comment_"+UserHolder.getUserId()+"_"+item.getId().toHexString();
                if(redisTemplate.hasKey(likekey)) {
                    vo.setHasLiked(0); //是否点赞
                }else{
                    vo.setHasLiked(1); //是否点赞
                }
                list.add(vo);
            }
        }
        //4、存入pageResult中
        result.setItems(list);
        //5、构造返回值
        return result;
    }

    //发布视频
    @CacheEvict(value="videoList",allEntries = true)
    public ResponseEntity saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、图片上传到阿里云OSS
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //2、视频上传到FastDFS
        String videoName = videoFile.getOriginalFilename();  //xasdsa/asdsaasd.avi
        String sufix = videoName.substring(videoName.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), sufix, null);//文件输入流，文件大小，文件的后缀名，null
        String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //3、构造video对象，并赋值
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setText("左手右手一个慢动作");
        video.setVideoUrl(videoUrl);
        video.setPicUrl(picUrl);
        //4、调用API保存
        videoApi.save(video);
        //5、构造返回值
        return ResponseEntity.ok(null);
    }


    //关注用户
    public ResponseEntity followUser(Long followUserId) {
        //1、创建对象 FollowUser,并赋值
        FollowUser user = new FollowUser();
        user.setUserId(UserHolder.getUserId());
        user.setFollowUserId(followUserId);
        //2、调用API
        videoApi.followUser(user);
        //3、将关注动作写入到redis
        String key = "followUser_"+UserHolder.getUserId()+"_"+followUserId;
        redisTemplate.opsForValue().set(key,"1");
        //4、构造返回值
        return ResponseEntity.ok(null);
    }

    //取消关注用户
    public ResponseEntity disFollowUser(Long followUserId) {
        //1、获取操作的用户id
        Long userId = UserHolder.getUserId();
        //2、调用API根据用户id和关注用户id，删除
        videoApi.disFollowUser(userId,followUserId);
        //3、将redis数据清空
        String key = "followUser_"+UserHolder.getUserId()+"_"+followUserId;
        redisTemplate.delete(key);
        //4、构造返回值
        return ResponseEntity.ok(null);
    }

    /**
     * 视频点赞
     */
    public ResponseEntity likeComment(String videoId) {
        //1、创建Conment对象
        Comment comment = new Comment();
        //2、设置对象属性
        comment.setPublishId(new ObjectId(videoId));
        comment.setUserId(UserHolder.getUserId());
        comment.setCommentType(1); //评论类型，1-点赞，2-评论，3-喜欢
        comment.setPubType(2); //操作数据  1、动态，2：视频，3：评论
        //3、调用API保存点赞数据，返回值点赞的总数
        long total = commentApi.save(comment);
        //4、将点赞记录存入redis数据库
        redisTemplate.opsForValue().set("video_like_comment_"+UserHolder.getUserId()+"_"+
                videoId, "1");
        return ResponseEntity.ok(total);
    }
}
